/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.huikecloud.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import org.springblade.common.constant.CommonConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Map;

/**
 * 文件下载 控制器
 *	CHFS_URL 需要和nginx配置保持一致
 * @author Blade
 * @since 2021-07-21
 */

@RestController
@RequestMapping("file")
public class FileController extends BladeController {

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 获取下载链接
	 */
	@GetMapping("/search/{name}")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "文件名", notes = "传入文件名")
	public String search(@PathVariable("name") String name) {
		String url = CommonConstant.CHFS_URL+"/chfs/search?str="+name;
		Map object = restTemplate.getForObject(url, Map.class);
		ArrayList<Map<String,Object>> files = (ArrayList) object.get("files");
		StringBuilder files_str= new StringBuilder();
		for (Map<String,Object> map:files) {
			files_str.append("wget ").append(CommonConstant.CHFS_URL).append("/chfs/shared/").append(map.get("name")).append("\n");
		}
		System.out.println(files_str);
		return files_str.toString();
	}

	//获取文件列表
	@GetMapping("/search")
	@ApiOperationSupport(order = 2)
	public String list() {
		String url = CommonConstant.CHFS_URL+"/chfs/files";
		Map object = restTemplate.getForObject(url, Map.class);
		ArrayList<Map<String,Object>> files = (ArrayList) object.get("files");
		StringBuilder files_str= new StringBuilder();
		for (Map<String,Object> map:files) {
			files_str.append(map.get("name")).append("\n");
		}
		System.out.println(files_str);
		return files_str.toString();
	}

}
